package com.dcjt.firehotcarpad.fragment

import LocationPool
import MapOperationEventPool
import NewMessagePool
import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.DividerItemDecoration
import com.amap.api.location.AMapLocation
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.model.LatLng
import com.aries.library.fast.module.fragment.FastRefreshLoadFragment
import com.aries.library.fast.retrofit.FastObserver
import com.aries.library.fast.util.FastStackUtil
import com.aries.library.fast.util.ToastUtil
import com.aries.ui.view.radius.RadiusTextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.base.BaseViewModelEntity
import com.dcjt.firehotcarpad.entity.BaseListEntity
import com.dcjt.firehotcarpad.model.HandleDisasterViewModel
import com.dcjt.firehotcarpad.moudle.NavActivity
import com.dcjt.firehotcarpad.retrofit1.repository.ApiRepository1
import com.dcjt.firehotcarpad.utils.MarkerToMapType
import com.dcjt.firehotcarpad.utils.MessageUtil
import com.dcjt.firehotcarpad.utils.StringUtils
import com.google.gson.annotations.SerializedName
import java.text.DecimalFormat
import kotlin.math.floor

/**
 * Created by cj on 2021/2/22.
 * Email:codesexy@163.com
 * Function:
 * desc:周边水源列表
 */
class WaterSourceFragment : FastRefreshLoadFragment<WaterSourceEntity>(),
    LocationPool.LocationChangeObserver, BaseQuickAdapter.OnItemChildClickListener,
    NewMessagePool.NewMessageObserverObserver {

    //type =1 位置周边  type = 2 警情周边
    companion object {
        fun newInstance( type:Int): WaterSourceFragment {
            var fragment = WaterSourceFragment()
            val bundle = Bundle()
            bundle.putInt("type", type)
            fragment.arguments = bundle
            return fragment
        }
    }
    @SuppressLint("UseRequireInsteadOfGet")
    override fun beforeInitView() {
        type = arguments?.get("type") as Int
        super.beforeInitView()
    }
    private var type: Int = -1
    private var currentPage: Int = 0
    private var zqid: String = ""
    private var currentZqid: String = ""
    private var currentLat: DoubleArray ?= null
    private var zqLat: DoubleArray ?= null
    lateinit var handleViewModel: HandleDisasterViewModel

    private lateinit var mAdapter: WaterSourceAdapter
    private lateinit var mViewModel: WaterSourceViewModel

    //之前的位置
    private var preLocation: AMapLocation? = null

    private var prePostTime: Long = 0

//    override fun getContentLayout(): Int = R.layout.fast_layout_multi_status_refresh_recycler
    override fun getContentLayout(): Int = R.layout.layout_fragment_water

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel = ViewModelProviders.of(this).get(WaterSourceViewModel::class.java)
        NewMessagePool.get().registerNewMessageObserver(this)
        mViewModel.listData.observe(
            this,
            Observer<BaseViewModelEntity<List<WaterSourceEntity>>> { entity ->
                mEasyStatusView.content()
                if (entity.isSuccess) {
                    val data = entity.data
                    if (data == null || data.isEmpty()) {
                        if (0 == DEFAULT_PAGE && mAdapter.data.size == 0) { //第一页就么有
                            mEasyStatusView.empty()
                        } else {
                            mAdapter.loadMoreEnd()
                        }
                        return@Observer
                    }
                    mAdapter.loadMoreComplete()

                    if (mRefreshLayout.isRefreshing && DEFAULT_PAGE === 0) {
                        mAdapter.setNewData(ArrayList())
                        mRefreshLayout.finishRefresh()
                    }

                    mAdapter.addData(data)
                    //在地图上撒点
                    renderPointOnMap()

                    if (data.size < DEFAULT_PAGE_SIZE) {
                        mAdapter.loadMoreEnd()
                    }
                } else {//失败
                    if (mRefreshLayout.isRefreshing) {
                        mRefreshLayout.finishRefresh();
                    } else {
                        if (mAdapter.data.size == 0) {
                            mEasyStatusView.error();
                        }
                    }
                }
            })

        //监听位置变化
        LocationPool.get().registerLocationObserver(this@WaterSourceFragment)

        mRecyclerView.addItemDecoration(
            DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)
        )

        mAdapter.onItemChildClickListener = this

        var rtv_my =  findViewById<RadiusTextView>(R.id.rtv_my)
        var rtv_zq =  findViewById<RadiusTextView>(R.id.rtv_zq)
        rtv_zq?.visibility = if (type == 2) View.VISIBLE else View.GONE
        rtv_my?.setOnClickListener {
            var pos: Array<Double>? = getCurrentPosition() ?: return@setOnClickListener
            currentLat =  MessageUtil.gcj02_To_Gps84(pos!![1], pos[0])
            currentZqid = ""
            rtv_zq?.isSelected = false
            rtv_my?.isSelected = true
            DEFAULT_PAGE = 0
            mRefreshLayout.autoRefresh()
            mEasyStatusView.loading()
        }
        rtv_zq?.setOnClickListener {
            if (zqLat== null){
                return@setOnClickListener
            }
            currentLat = zqLat
            currentZqid = zqid
            rtv_zq?.isSelected = true
            rtv_my?.isSelected = false
            DEFAULT_PAGE = 0
            mRefreshLayout.autoRefresh()
            mEasyStatusView.loading()

        }
        handleViewModel =
            ViewModelProviders.of(requireActivity()).get(HandleDisasterViewModel::class.java)
        handleViewModel.getDisasterInfo().observe(this, androidx.lifecycle.Observer { entity ->
            //判断警情信息zqxx是否为空    为空：警情结束，弹出弹框《只有一个车》    不为空：多个车   页面保存
            if (entity != null) {
                if (entity!!.zqxx != null) {
                    zqid = entity!!.zqxx!!.id!!
                    if(entity!!.zqxx!!.gisX != null && !StringUtils.isEmpty(entity!!.zqxx!!.gisX!!)){
                        zqLat =  MessageUtil.gcj02_To_Gps84( entity!!.zqxx!!.gisX!!.toDouble(), entity!!.zqxx!!.gisY!!.toDouble())
                    }
                }}
        })

    }


    private fun renderPointOnMap() {
        MapOperationEventPool.get()
            .sendAroundWaterMakersDispatch(mAdapter.data, MarkerToMapType.MARKER_ADD,currentPage)
    }

    override fun onChange(location: AMapLocation) {
        var needGetResource = false

        if (preLocation != null) {
            val lineDistance = AMapUtils.calculateLineDistance(
                LatLng(preLocation!!.latitude, preLocation!!.longitude),
                LatLng(location.latitude, location.longitude)
            )
            val floor = floor(lineDistance.toDouble())
            //距离大于100m
            needGetResource = floor > 300
        }

        preLocation = location
        //距离大于100米  且 时间超过了 5s
        needGetResource = needGetResource &&
                (System.currentTimeMillis() - prePostTime > 5 * 1000)

        if (needGetResource) {
            DEFAULT_PAGE = 0
            mRefreshLayout.autoRefresh()
        }
    }

    override fun onRefreshWaterList() {
        mRefreshLayout.autoRefresh()
        mEasyStatusView.loading()
    }


    override fun onDestroy() {
        super.onDestroy()
        LocationPool.get().unRegisterLocationObserver(this)
    }

    override fun loadData(page: Int) {
        prePostTime = System.currentTimeMillis()

        if (StringUtils.isEmpty(currentZqid)){
            var pos: Array<Double>? = getCurrentPosition() ?: return
            currentLat =  MessageUtil.gcj02_To_Gps84(pos!![1], pos[0])
        }
        currentPage = page
        currentLat?.let { mViewModel.loadData(page, it,currentZqid) }
    }

    override fun getAdapter(): BaseQuickAdapter<WaterSourceEntity, BaseViewHolder> =
        WaterSourceAdapter().apply { mAdapter = this }

    override fun onItemChildClick(
        adapter: BaseQuickAdapter<*, *>?,
        clicKView: View?,
        position: Int
    ) {
        var entity = adapter!!.data[position] as WaterSourceEntity
//
        when (clicKView!!.id) {
            R.id.container -> {
                MapOperationEventPool.get()
                    .sendAroundWaterMakersDispatch(
                        mutableListOf(entity),
                        MarkerToMapType.MARKER_IMITATE_CLICK
                    )
            }
            R.id.ivNav -> {
                try {
                    val lon = entity.gisX?.toBigDecimal()?.toDouble()!!
                    val lat = entity.gisY?.toBigDecimal()?.toDouble()!!
                    NavActivity.startNavActivity(FastStackUtil.getInstance().current, lat, lon)
                } catch (e: Exception) {
                    e.printStackTrace()
                    ToastUtil.show("数据有问题，请检查")
                }
            }
        }
    }
    private fun getCurrentPosition(): Array<Double>? {
        val location = LocationPool.get().getCurrentLocation()
        return if (location == null) {
            null
        } else {
            var lat = location.latitude
            var lon = location.longitude
            arrayOf(lon, lat)
        }
    }


}

class WaterSourceViewModel : ViewModel() {

    var listData: MutableLiveData<BaseViewModelEntity<List<WaterSourceEntity>>> =
        MutableLiveData()

    fun loadData(page: Int,array:DoubleArray,zqid:String) {

//        val array = MessageUtil.gcj02_To_Gps84(pos[1], pos[0])

//        自贡地址测试
//        ApiRepository1.getInstance().getWaterSource(zqid,104.728247, 29.353015, 1000, page, if (StringUtils.isEmpty(zqid)) "wdzb" else "zqzb",!StringUtils.isEmpty(zqid))
        ApiRepository1.getInstance().getWaterSource(zqid,array[1], array[0], 1000, page, if (StringUtils.isEmpty(zqid)) "wdzb" else "zqzb",!StringUtils.isEmpty(zqid))
//        ApiRepository1.getInstance().getWaterSource(zqid,array[1], array[0], 1000, page,zblb)
            .subscribe(object : FastObserver<BaseListEntity<WaterSourceEntity>>() {
                override fun _onNext(entity: BaseListEntity<WaterSourceEntity>) {
                    listData.postValue(BaseViewModelEntity(entity.records, true))
                }

                override fun _onError(errorRes: Int, errorCode: Int, e: Throwable) {
                    super._onError(errorRes, errorCode, e)
                    listData.postValue(BaseViewModelEntity(isSuccess = false))
                }
            })
    }

}

data class CarEntity(
    @SerializedName("cljc")
    val cljc: String?,
    @SerializedName("clmc")
    val clmc: String?,
    @SerializedName("cphm")
    val cphm: String?,
    @SerializedName("dept_id")
    val deptId: String?,
    @SerializedName("dept_name")
    val deptName: String?,
    @SerializedName("id")
    val id: String?,
    @SerializedName("syid")
    val syid: String?
)

//周边水源
data class WaterSourceEntity(
    @SerializedName("bz") val bz: Any?,
    @SerializedName("dept_id") val deptId: Any?,
    @SerializedName("dept_name") val deptName: Any?,
    @SerializedName("fwtb") val fwtb: Any?,
    @SerializedName("fwtd") val fwtd: Any?,
    @SerializedName("fwtn") val fwtn: Any?,
    @SerializedName("fwtx") val fwtx: Any?,
    @SerializedName("gis_x") val gisX: String?,
    @SerializedName("gis_y") val gisY: String?,
    @SerializedName("id") val id: String?,
    @SerializedName("jzsj") val jzsj: Any?,
    @SerializedName("kyzt") val kyzt: Int?,
    @SerializedName("qsxs") val qsxs: String?,
    @SerializedName("qysj") val qysj: Any?,
    @SerializedName("sybh") val sybh: Any?,
    @SerializedName("sydz") val sydz: String?,
    @SerializedName("sylx") val sylx: String?,
    @SerializedName("sylxmc") val sylxmc: String?,
    @SerializedName("symc") val symc: String?,
    @SerializedName("wbdw") val wbdw: Any?,
    @SerializedName("wbdwdh") val wbdwdh: Any?,
    @SerializedName("xz") val xz: String?,
    @SerializedName("xzmc") val xzmc: String?,
    @SerializedName("xzqhdm") val xzqhdm: Any?,
    @SerializedName("zpslt") val zpslt: Any?,
    @SerializedName("zpwjurl") val zpwjurl: Any?,
    @SerializedName("clsyqk") val clsyqk: Any?,
    @SerializedName("ll") val ll: Any?,
    @SerializedName("yl") val yl: Any?,
    @SerializedName("zj") val zj: Any?,
    @SerializedName("cls") val cls: Any?,
    @SerializedName("cldata") val cldata: List<CarEntity>?,
    @SerializedName("zxjl") val zxjl: Int?
) {
    override fun equals(other: Any?): Boolean {
        if (other !is WaterSourceEntity) {
            return false
        }
        return TextUtils.equals(other.id, id)
    }

    override fun hashCode(): Int {
        return kyzt ?: 0 + (zxjl ?: 0)
    }
}

class WaterSourceAdapter(private var format: DecimalFormat = DecimalFormat("0.#")) :
    BaseQuickAdapter<WaterSourceEntity, BaseViewHolder>(R.layout.item_around_water) {

    override fun convert(helper: BaseViewHolder?, item: WaterSourceEntity?) {
        helper!!
        item!!
        helper.setText(R.id.tv_name, "${item.symc} - ${item.sylxmc}")
            .setText(R.id.tvAddress, item.sydz)
            .setText(R.id.tvDistance, "${item.zxjl}m")

            .setText(R.id.rtv_gj, "管径${StringUtils.getNoNullString(item.zj.toString(),"0")}mm")
            .setText(R.id.rtv_sy, "水压${StringUtils.getNoNullString(item.yl.toString(),"0")}Mpa")
            .setText(R.id.rtv_ll, "流量${StringUtils.getNoNullString(item.ll.toString(),"0")}L/S")
        var syqk =helper.getView<RadiusTextView>(R.id.rtv_syqk)
        syqk.visibility = View.VISIBLE
        var ms ="";
        when {
            StringUtils.isEmpty(item.cls.toString()) -> {
                syqk.visibility = View.GONE
            }
            item.cls.toString() == "0" -> {
                ms = "暂无车辆使用"
                syqk.isSelected = false
                syqk.isSelected = false
            }
            else -> {
                ms = "${item.cls}车在使用"
                syqk.isSelected = true
            }
        }
        helper.setText(R.id.rtv_syqk, ms)


        if (item.zxjl != null && item.zxjl > 1000) {
            helper.setText(R.id.tvDistance, "${format.format(item.zxjl / 1000)}km")
        }


        helper.addOnClickListener(R.id.container)
        helper.addOnClickListener(R.id.ivNav)
    }

}